<?php 
class Images_Model_Storage_Local {

	public function cancel($filename,$image_path) {

		$cnf = Zend_Registry::get('cnf');
        $root=$cnf->path->root;
        $root=preg_replace('/[\\/,\\\]$/','',trim($root));
		$image_path='/'.preg_replace('/^[\\/,\\\]/','',trim($image_path));
        $real_image_path=$root.$image_path;
        preg_match ( '/\S+\.(\S+)$/', $filename, $out );
     	$res['type'] = mb_strtolower($out [1],'UTF-8');
		$file='tmp_'.md5($filename).'.'.$res['type'];
		if(file_exists($file))
		{
			unlink($file);
		}
		return array('success',true);
	}
	
	public function load($id){
		
		$root=ROOT_PATH;
		
		$model=new Images_Model_Imageslist();
		$select=$model->select();
		$select->setColumns(
			array('id','width','height','img_url','thumb_url','crop','alt','path')
		);
		
		$res=$select->getOne("`id`='".$id."'");
		if($res!=false){
			if(file_exists($root.$res['path'])){
				unset($res['path']);
				$res['success']=true;
				return $res;
			}else{
			$res['success']=false;
			$res['id']=$id;
			return $res;
			}
		}else{
			$res['success']=false;
			$res['id']=$id;
			return $res;
		}
	}
	
	public function update($id,$params){
	    $imagesList=new Images_Model_Imageslist();
	    foreach ($params as $key=>$value){
	    	if(trim($value)==""){
	    	unset($params[$key]);
	    	}
	    }
		return  ($imagesList->update($id,$params));
	}
	
	public function upload($image_path,$thumb_path,$link=false)
	{
		
		
        $imgSettings=new Zend_Config_Ini(APPLICATION_PATH.'/modules/images/settings/images_settings.ini');
   
        $root=ROOT_PATH;
		$image_path='/'.preg_replace('/^[\\/,\\\]/','',trim($image_path));
		$thumb_path='/'.preg_replace('/^[\\/,\\\]/','',trim($thumb_path));
        $real_image_path=$root.$image_path;
	    $real_thumb_path=$root.$thumb_path;        
        
		if (! file_exists ( $real_image_path )) {
			mkdir ( $real_image_path,0777,true );
		}
		
		if (! file_exists ( $real_thumb_path )) {
			mkdir ( $real_thumb_path,0777,true );
		}
	    
        $imgSettings=$imgSettings->toArray();
        
	    $extensions=explode(',',$imgSettings['allowed_extensions']);

        $max_upload = (int)(ini_get('upload_max_filesize'));
        $max_post = (int)(ini_get('post_max_size'));
        $memory_limit = (int)(ini_get('memory_limit'));
        $limit = min($max_upload, $max_post, $memory_limit)*1024*1024*8;        
      
        if(!$link){
        	$res=Images_Model_Upload::upload($real_image_path,$extensions,$limit);
        }
        else{
        	$res=array();
        	$res['errors']='';
        	/*
        	preg_match ( '/\S+\.(\S+)$/', $link, $out );
			$name_short = preg_replace ( '/\\.\\D*$/ui', '', $link );
			$type = mb_strtolower($out [1],'UTF-8');
			$res['type']=$type;
			$newname='tmp'.md5($link).$type;
			$res['name']=$newname;
			*/
        	
			
			
			$size=getimagesize($link);
			if(!isset($size['mime'])){
				$res['errors']='Unable to get file type';
				$e=new Zend_Exception('Unable to get file type');
				throw $e;
			}
			
			$type=preg_replace('/^.*\\//', '', $size['mime']);
			if($type=="jpeg"){
				$type="jpg";
			}
			
			
			$newname='tmp'.md5($link).'.'.$type;
			
			
        	$img=file_get_contents($link);
        	if(!$img){
        		$res['errors']='Unable to get file content';
        		$e=new Zend_Exception('Unable to get file content');
				throw $e;
				
        	}
        	$res['type']=$type;
			$res['name']=$newname;
        	file_put_contents($real_image_path . $newname,$img);
        }
        
        
        
        
		$result=array();

        if($res['errors']=="")
        {   
        	
            
        	$imagesList = new Images_Model_Imageslist ();
		    
        	$source=$real_image_path.$res['name'];
        	
        	$id = $imagesList->create(array('type'=>$res['type']));
		    
			
			$res ['path'] = $real_image_path.$id.".".$res['type'];
			
			
			
			$filter = new Zend_Filter_File_Rename ( array ($source, 'target' => $res ['path'],'overwrite' => true));
			$filter->addFile ( array ($source, 'target' => $res ['path'],'overwrite' => true));
			$filter->filter ($source);
				
			$imagesList->update($id,array(
				'path'=>$image_path.$id.".".$res['type']
			));
			
			
			$helper=new Zen_View_Helper_Image_Multi();
			
			
			//Resize to Max Height and Max Width
			$resized=$helper->image_Multi($id)->resize($imgSettings['max_width'], $imgSettings['max_height'],'outside','down')->getUrl();
			$img=file_get_contents(ROOT_PATH.$resized);
			file_put_contents($res['path'], $img);
			
			
			//Create thumb
        	$helper=new Zen_View_Helper_Image_Multi();
			$resized=$helper->image_Multi($id)->resize(120, 120,'inside','down')->getUrl();
			$img=file_get_contents(ROOT_PATH.$resized);
			
			file_put_contents($real_thumb_path.$id.".".$res['type'], $img);
			
            
            $size = getimagesize($res['path']);
			
        	
        	
        	$width=$size[0];
        	$height=$size[1];

            $result['thumb_url']=$thumb_path.$id.".".$res['type'];
            $res['image_url']=$image_path.$id.".".$res['type'];
            
            $imagesList->update($id,
            					array(
            						'path'=>$image_path.$id.".".$res['type'],
            						'img_url'=>$image_path.$id.".".$res['type'],
            						'thumb_url'=>$result['thumb_url'],
            						'width'=>$width,
            						'height'=>$height
            					));
            $result['success']=true;
            $result['id']=$id;
        }else{
        	unlink($real_image_path.$res ['name']);
            $result['success']=false;
            $result['errors']=$res['errors'];
        }        
        return $result;
	}
    

}